package com.hypertech.core.ffmpeg.controller;

import com.hypertech.core.ffmpeg.model.Job;
import com.hypertech.core.ffmpeg.service.JobService;
import com.hypertech.core.ffmpeg.service.VideoService;
import com.hypertech.core.ffmpeg.videoDao.FileInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;
@Slf4j
@Controller
@RequestMapping("/video")
public class VideoController {
    private final String VIDEO_FILE_TYPE = ".mp4";
    private final String IMAGE_FILE_TYPE = ".jpg";
    private boolean flag = false;
   /* ffmpeg能解析的格式：（asx，asf，mpg，wmv，3gp，mp4，mov，avi，flv等）*/
    private static String[] UPLOAD_VIDEO_SUPPORT_TYPE={".avi",".mp4",".flv",".3gp",".asx",".asf",".mpg",".wmv",".mov",".mkv"};

    @Autowired
    private VideoService videoService;

    @Autowired
    private JobService jobService;

    @Value("${ffmpeg.savePath}")
    private String savePath;

    @Value("${ffmpeg.convertPath}")
    private String convertPath;

    @RequestMapping("/upload")
    public String upload(MultipartFile video, String wm, String level, Model model) throws Exception {

        if (video.getSize() <= 0){
            model.addAttribute("msg","请上传文件");
            return "error/5xx";
        }

        File savepath = new File(savePath);
        File convertpath = new File(convertPath);
        FileInfo.mkDir(savepath);
        FileInfo.mkDir(convertpath);

        String originalFilename = video.getOriginalFilename();//上传文件名
        String postName = originalFilename.substring(originalFilename.lastIndexOf("."));//原文件后缀名
        for (int i = 0; i < UPLOAD_VIDEO_SUPPORT_TYPE.length; i++) {
            if (!UPLOAD_VIDEO_SUPPORT_TYPE[i].equals(postName) && i>=UPLOAD_VIDEO_SUPPORT_TYPE.length-1){
                model.addAttribute("msg","不支持该上传文件格式");
                return "error/5xx";
            }else if (UPLOAD_VIDEO_SUPPORT_TYPE[i].equals(postName)){
                break;
            }
        }
        UUID uuid = UUID.randomUUID();
        String filename= uuid + postName;
        File newFile =new File(savePath+filename);
        try {
            video.transferTo(newFile);//先保存上传的文件到指定目录
        } catch (IOException e) {
            return e.getMessage();
        }
        String src = savePath+filename;//源文件绝对路径
        String destprefix=convertPath+uuid;//转换文件名前缀
        /*视频*/
        String dest = destprefix+VIDEO_FILE_TYPE;
        String font = "./font/simhei.ttf";
        String text = "测试TEST";
        String textwatermark = "\"drawtext=fontfile="+font+": text='"+text+"':x=10:y=10:fontsize=50:fontcolor=red\"";
        /*ffmpeg.exe -y -i 1.mp4 -vf "movie=info.png[wm];[in][wm] overlay=100:100"  -b:v 1024k c.flv*/
        String image = "./image/info.png";
        String imagewatermark = "\"movie="+image+" [wm];[in][wm] overlay=10:10\"";
        /*计算执行时间*/
        long startTime=System.currentTimeMillis();
        /*水印二者选其一*/
        if (!StringUtils.isEmpty(wm)){
            if ("0".equals(wm)){
                /*转码等级1[slow] 2[middle] 3[high]*/
                if (!StringUtils.isEmpty(level))
                    if ("1".equals(level)) {
                        flag = videoService.low(src, dest, imagewatermark, null);//图片水印
                    }else if ("3".equals(level)) {
                        flag = videoService.high(src, dest, imagewatermark, null);
                    }else {
                        flag = videoService.middle(src, dest, imagewatermark, null);
                    }
            }else if ("1".equals(wm)) {
                if (!StringUtils.isEmpty(level))
                    if ("1".equals(level)) {
                        flag = videoService.low(src, dest, null, textwatermark);//文字水印
                    }else if ("3".equals(level)) {
                        flag = videoService.high(src, dest, null, textwatermark);
                    }else {
                        flag = videoService.middle(src, dest, null, textwatermark);
                    }
            }else {
                if (!StringUtils.isEmpty(level))
                    if ("1".equals(level)) {
                        flag = videoService.low(src, dest, null, null);//无水印
                    }else if ("3".equals(level)) {
                        flag = videoService.high(src, dest, null, null);
                    }else {
                        flag = videoService.middle(src, dest, null, null);
                    }
            }
        }
        /*计算执行时间*/
        long endTime=System.currentTimeMillis();
        float excTime=(float)(endTime-startTime)/1000;
        log.error("+++++++++执行时间++++++++++："+excTime+"s");
       /*截图*/
        dest = destprefix+IMAGE_FILE_TYPE;
        if (flag) {
            videoService.screenshots(src, dest, 8);
            /*数据库保存*/
            Job job = new Job();
            job.setId(uuid.toString());
            job.setName(uuid.toString());
            job.setPhoto(uuid+IMAGE_FILE_TYPE);
            job.setVideo(uuid+VIDEO_FILE_TYPE);
            jobService.add(job);
        }
        /*删除源文件*/
        File deleteFile = new File(src);
        if (deleteFile.exists()){
            deleteFile.delete();
        }

        model.addAttribute("videoId",uuid);
        if (flag)
            return "/videojs/gotoShow";
        return "videojs/error";
    }
}
